import React, { useEffect, useState } from 'react'
import './index.css'
import { Button, DatePicker, Form, Input, Modal, Popconfirm, Radio, Space, Table } from 'antd'
import { listTableData, addTableData, editTableData, deleteTableData } from '@/api/user';
import dayjs from 'dayjs'
const { Column } = Table;

const options = [
  { label: '男', value: 'male' },
  { label: '女', value: 'female' }
];

export default function Index() {

  const [form] = Form.useForm();

  const [tableData, setTableData] = useState([])
  const [infnOpen, setInfnOpen] = useState(false)
  const [modelTitle, setModelTitle] = useState("")

  useEffect(() => {
    getTableData()
  }, [])

  // 请求列表接口
  const getTableData = async () => {
    const res = await listTableData()
    console.log("res=>", res)
    setTableData(res.data)
  }

  // 打开弹窗
  const handleOpen = (type) => {
    if (type === 'add') {
      setModelTitle("新增用户")
    } else {
      setModelTitle("编辑用户")
    }
    setInfnOpen(true)
  }

  // 信息弹窗确认
  const handleOk = () => {
    setInfnOpen(false)
    form.resetFields();
  }

  // 信息弹窗取消
  const handleCancel = () => {
    setInfnOpen(false)
    form.resetFields();
  }

  // 处理表单提交
  const onFinish = (values) => {
    form.validateFields().then(async () => {
      if (modelTitle === '新增用户') {
        const data = form.getFieldsValue()
        const params = {
          ...data,
          birthday: dayjs(data.birthday, "YYYY-MM-DD").format("YYYY-MM-DD"),
          age: calculateAge(data.birthday)
        }
        await addTableData(params)
        setInfnOpen(false)
        form.resetFields();
        getTableData()
      } else {
        const data = form.getFieldsValue()
        const params = {
          ...data,
          birthday: dayjs(data.birthday, "YYYY-MM-DD").format("YYYY-MM-DD"),
          age: calculateAge(data.birthday)
        }
        // 编辑数据
        await editTableData(params)
        setInfnOpen(false)
        form.resetFields();
        getTableData()
      }
    })
  };

  // 删除
  const deleteData = async (id) => {
    await deleteTableData({ id: id })
    getTableData()
  }

  // 编辑
  const editData = (item) => {
    console.log("item=>", item)
    setModelTitle("编辑用户")
    setInfnOpen(true)
    form.setFieldsValue({
      ...item,
      birthday: dayjs(item.birthday)
    });
  }

  // 计算年龄
  const calculateAge = (birthday) => {
    // 将出生日期转换为 Date 对象
    const birth = new Date(birthday);
    const today = new Date();

    // 计算年龄
    let age = today.getFullYear() - birth.getFullYear();
    const monthDifference = today.getMonth() - birth.getMonth();

    // 如果当前日期还没有到出生日期的月份，则需要减去 1 岁
    if (monthDifference < 0 || (monthDifference === 0 && today.getDate() < birth.getDate())) {
      age--;
    }

    return age;
  };


  return (
    <>
      <div className='user-container'>
        <div className='user-top'>
          <Button type="primary" onClick={() => handleOpen('add')}>新增</Button>
          <Form name="search" layout='inline'>
            <Form.Item className='user-top-input'>
              <Input placeholder="用户名" />
            </Form.Item>
            <Form.Item>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </Form.Item>
          </Form>
        </div>
        <div className='use-table'>
          <Table dataSource={tableData} rowKey='id'>
            <Column title="姓名" dataIndex="name" key="name" width={150} />
            <Column title="年龄" dataIndex="age" key="age" width={100} />
            <Column
              title="性别"
              dataIndex="sex"
              key="sex"
              width={100}
              render={(sex) => (sex === 'male' ? '男' : sex === 'female' ? '女' : '')}
            />
            <Column title="出生日期" dataIndex="birthday" key="birthday" width={180} />
            <Column title="地址" dataIndex="address" key="address" />
            <Column title="操作" dataIndex="controls" key="controls" width={300}
              render={(_, record) => (
                <Space size="middle">
                  <Button color="default" variant="outlined" onClick={() => editData(record)}>编辑</Button>
                  <Popconfirm
                    description="确认要删除吗"
                    okText="确定"
                    cancelText="取消"
                    onConfirm={() => deleteData(record.id)}
                  >
                    <Button color="danger" variant="solid">删除</Button>
                  </Popconfirm>
                </Space>
              )} />
          </Table>
        </div>
      </div>
      {/* 新增编辑弹窗 */}
      <div className='user-info-modal'>
        <Modal
          open={infnOpen}
          title={modelTitle}
          onOk={handleOk}
          onCancel={handleCancel}
          footer={null}
        >
          <Form
            form={form}
            name="userForm"
            labelCol={{ span: 4 }}
            wrapperCol={{ span: 16 }}
            initialValues={{ remember: true }}
            onFinish={onFinish} // 提交时校验并调用
            autoComplete="off"
          >
            <Form.Item
              label="id"
              name="id"
              hidden
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="姓名"
              name="name"
              rules={[{ required: true, message: '请输入姓名' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item
              label="性别"
              name="sex"
              rules={[{ required: true, message: '请选择性别' }]}
            >
              <Radio.Group options={options} block />
            </Form.Item>
            <Form.Item
              label="出生日期"
              name="birthday"
              rules={[{ required: true, message: '请选择出生日期' }]}
            >
              <DatePicker placeholder="请选择出生日期" style={{ width: '100%' }} />
            </Form.Item>
            <Form.Item
              label="地址"
              name="address"
              rules={[{ required: true, message: '请输入地址' }]}
            >
              <Input />
            </Form.Item>
            <Form.Item>
              <div className='modal-footer'>
                <Button onClick={handleCancel} type="default">
                  取消
                </Button>
                <Button type="primary" htmlType="submit">
                  提交
                </Button>
              </div>
            </Form.Item>
          </Form>
        </Modal>
      </div>
    </>

  )
}
